// -*-c++-*-

#include <string>
using namespace std;

#include <constants.hpp>

#include "global.hpp"
#include "table_schema.hpp"
#include "table_schema_manager.hpp"

#include "table.hpp"

namespace xbase {
	
	table::table (const std::string &p_table_name)
		: m_table_name(p_table_name)
	{
	}

	tablet::pointer table::get_tablet(const std::string &p_tablet_name) const
	{
		Guard<ReadWriteLock::ReadLock> _guard(m_tablets_lock.read_lock());
		const tablet_map::const_iterator iter = m_tablets.find(p_tablet_name);
		tablet::pointer _tablet; // default value
		if (iter != m_tablets.end())
		{
			_tablet = iter->second;
		}
		return _tablet;
	}

	// 在这里添加，即表示该子表上线
	void table::add_tablet(const tablet::pointer &p_tablet)
	{
		// update log sequence number, 保证日志序列号是最大的
		// 只需在子表成功加载并在线才需要更新，放在这里也无所谓
		global::the_log_manager->logger().update_sequence_number(p_tablet->max_sequence_number());

		Guard<ReadWriteLock::WriteLock> _gurad(m_tablets_lock.write_lock());
		std::pair<tablet_map::iterator, bool>
			ret_val = m_tablets.insert(tablet_map::value_type(p_tablet->tablet_name(),
									  p_tablet));
		assert(ret_val.second == true); (void)ret_val;
		// if (ret_val.second == false)
		// {
		// 	// TODO:
		// 	//LOG();
		// 	// throw
		// }
	}

	bool table::is_loaded(const std::string &p_tablet_name) const
	{
		Guard<ReadWriteLock::ReadLock> _guard(m_tablets_lock.read_lock());
		const tablet_map::const_iterator iter = m_tablets.find(p_tablet_name);
		return (iter != m_tablets.end());
	}

	table_schema::pointer table::get_schema() const
	{
		if (m_schema.expired())
		{
			Guard<FastLock> _guard(m_schema_lock);
			if (m_schema.expired())
			{
				m_schema = global::the_schema_manager->get_schema(this->table_name());
			}
		}
		return m_schema.lock();
	}

}



